home *** CD-ROM | disk | FTP | other *** search
- Path: ts17-13.tor.InfoRamp.Net!pitchl
- From: pitchl@tdbank.ca (Lew Pitcher)
- Newsgroups: comp.lang.c
- Subject: Re: why is this an infinite loop?
- Date: Sat, 20 Jan 1996 03:06:16
- Organization: Toronto Dominion Bank
- Message-ID: <pitchl.44.00031AE4@tdbank.ca>
- References: <4dp9p5$jm2@news1.wolfe.net>
- NNTP-Posting-Host: ts17-13.tor.inforamp.net
- X-Newsreader: Trumpet for Windows [Version 1.0 Rev A]
-
- In article <4dp9p5$jm2@news1.wolfe.net> neus@wolfenet.com (Bill Campbell) writes:
-
- >Beginning c student can't figure out why this small function to read in a
- >value for the variable x causes an infinite loop when it receives unexpected
- >input.
-
- >double get_x()
- >{
- > int test;
- > double x;
-
- > printf("Enter a numeric value for x: ");
-
- > while(scanf("%lf", &x) != 1)
- > {
- > printf("ERROR - program expecting a number");
- > printf("Enter a numeric value for x: ");
- > }
-
- > return x;
- >}
-
- According to the manual, scanf() will terminate "when an input character
- conflicts with the control string. If conversion terminates on a conflicting
- input character, the offending input character is left unread in the input
- stream."
- This means that if you answered
-
- X
-
- to the prompt, the %lf conversion fails and 'X' stays in the buffer for the
- next time scanf() is executed, and is *still* invalid for a %lf conversion.
- Thus the conversion again fails, again leaving the invalid chars in the buffer
- and so on.
-
- What you need to do is clean them out (with another scanf() or something)
- before reissueing the scanf("%lf",&x).
-
- Lew Pitcher | "I'm a little source code
- Toronto Dominion Bank | Short and Stout
- ======================= | Here is my Input,
- Enzo Matrix - Reboot | And here is my out"
-